{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "google",
   "metadata": {},
   "source": [
    "##### Copyright 2023 Google LLC."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "apache",
   "metadata": {},
   "source": [
    "Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "you may not use this file except in compliance with the License.\n",
    "You may obtain a copy of the License at\n",
    "\n",
    "    http://www.apache.org/licenses/LICENSE-2.0\n",
    "\n",
    "Unless required by applicable law or agreed to in writing, software\n",
    "distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "See the License for the specific language governing permissions and\n",
    "limitations under the License.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "basename",
   "metadata": {},
   "source": [
    "# simple_pdlp_program"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "link",
   "metadata": {},
   "source": [
    "<table align=\"left\">\n",
    "<td>\n",
    "<a href=\"https://colab.research.google.com/github/google/or-tools/blob/main/examples/notebook/pdlp/simple_pdlp_program.ipynb\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/colab_32px.png\"/>Run in Google Colab</a>\n",
    "</td>\n",
    "<td>\n",
    "<a href=\"https://github.com/google/or-tools/blob/main/ortools/pdlp/samples/simple_pdlp_program.py\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/github_32px.png\"/>View source on GitHub</a>\n",
    "</td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "doc",
   "metadata": {},
   "source": [
    "First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "install",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install ortools"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "description",
   "metadata": {},
   "source": [
    "\n",
    "Solves a simple LP using PDLP's direct Python API.\n",
    "\n",
    "Note: The direct API is generally for advanced use cases. It is matrix-based,\n",
    "that is, you specify the LP using matrices and vectors instead of algebraic\n",
    "expressions. You can also use PDLP via the algebraic pywraplp API (see\n",
    "linear_solver/samples/simple_lp_program.py).\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "code",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import scipy.sparse\n",
    "\n",
    "from ortools.pdlp import solve_log_pb2\n",
    "from ortools.pdlp import solvers_pb2\n",
    "from ortools.pdlp.python import pdlp\n",
    "from ortools.init.python import init\n",
    "\n",
    "\n",
    "def simple_lp() -> pdlp.QuadraticProgram:\n",
    "    \"\"\"Returns a small LP.\n",
    "\n",
    "    min 5.5 x_0 - 2 x_1 - x_2 +   x_3 - 14 s.t.\n",
    "        2 x_0 +     x_1 +   x_2 + 2 x_3  = 12\n",
    "          x_0 +             x_2          <=  7\n",
    "        4 x_0                            >=  -4\n",
    "       -1 <=            1.5 x_2 -   x_3  <= 1\n",
    "      -infinity <= x_0 <= infinity\n",
    "             -2 <= x_1 <= infinity\n",
    "      -infinity <= x_2 <= 6\n",
    "            2.5 <= x_3 <= 3.5\n",
    "    \"\"\"\n",
    "    lp = pdlp.QuadraticProgram()\n",
    "    lp.objective_offset = -14\n",
    "    lp.objective_vector = [5.5, -2, -1, 1]\n",
    "    lp.constraint_lower_bounds = [12, -np.inf, -4, -1]\n",
    "    lp.constraint_upper_bounds = [12, 7, np.inf, 1]\n",
    "    lp.variable_lower_bounds = [-np.inf, -2, -np.inf, 2.5]\n",
    "    lp.variable_upper_bounds = [np.inf, np.inf, 6, 3.5]\n",
    "    # Most use cases should initialize the sparse constraint matrix without\n",
    "    # constructing a dense matrix first! We use a np.array here for convenience\n",
    "    # only.\n",
    "    constraint_matrix = np.array(\n",
    "        [[2, 1, 1, 2], [1, 0, 1, 0], [4, 0, 0, 0], [0, 0, 1.5, -1]]\n",
    "    )\n",
    "    lp.constraint_matrix = scipy.sparse.csc_matrix(constraint_matrix)\n",
    "    return lp\n",
    "\n",
    "\n",
    "def main() -> None:\n",
    "    params = solvers_pb2.PrimalDualHybridGradientParams()\n",
    "    # Below are some common parameters to modify. Here, we just re-assign the\n",
    "    # defaults.\n",
    "    optimality_criteria = params.termination_criteria.simple_optimality_criteria\n",
    "    optimality_criteria.eps_optimal_relative = 1.0e-6\n",
    "    optimality_criteria.eps_optimal_absolute = 1.0e-6\n",
    "    params.termination_criteria.time_sec_limit = np.inf\n",
    "    params.num_threads = 1\n",
    "    params.verbosity_level = 0\n",
    "    params.presolve_options.use_glop = False\n",
    "\n",
    "    # Call the main solve function.\n",
    "    result = pdlp.primal_dual_hybrid_gradient(simple_lp(), params)\n",
    "    solve_log = result.solve_log\n",
    "\n",
    "    if solve_log.termination_reason == solve_log_pb2.TERMINATION_REASON_OPTIMAL:\n",
    "        print(\"Solve successful\")\n",
    "    else:\n",
    "        print(\n",
    "            \"Solve not successful. Status:\",\n",
    "            solve_log_pb2.TerminationReason.Name(solve_log.termination_reason),\n",
    "        )\n",
    "\n",
    "    # Solutions vectors are always returned. *However*, their interpretation\n",
    "    # depends on termination_reason! See primal_dual_hybrid_gradient.h for more\n",
    "    # details on what the vectors mean if termination_reason is not\n",
    "    # TERMINATION_REASON_OPTIMAL.\n",
    "    print(\"Primal solution:\", result.primal_solution)\n",
    "    print(\"Dual solution:\", result.dual_solution)\n",
    "    print(\"Reduced costs:\", result.reduced_costs)\n",
    "\n",
    "    solution_type = solve_log.solution_type\n",
    "    print(\"Solution type:\", solve_log_pb2.PointType.Name(solution_type))\n",
    "    for ci in solve_log.solution_stats.convergence_information:\n",
    "        if ci.candidate_type == solution_type:\n",
    "            print(\"Primal objective:\", ci.primal_objective)\n",
    "            print(\"Dual objective:\", ci.dual_objective)\n",
    "\n",
    "    print(\"Iterations:\", solve_log.iteration_count)\n",
    "    print(\"Solve time (sec):\", solve_log.solve_time_sec)\n",
    "\n",
    "\n",
    "init.CppBridge.init_logging(\"simple_pdlp_program.py\")\n",
    "cpp_flags = init.CppFlags()\n",
    "cpp_flags.stderrthreshold = 0\n",
    "cpp_flags.log_prefix = False\n",
    "init.CppBridge.set_flags(cpp_flags)\n",
    "main()\n",
    "\n"
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 5
}
